//
//  OSCEmoticonPackage.m
//  OSCEmoctionTools
//
//  Created by 8b410-2 on 17/1/6.
//  Copyright © 2017年 abb. All rights reserved.
//

#import "OSCEmoticonPackage.h"
#import "OSCEmoticonCollectionView.h"
#import "OSCEmoticonAttachment.h"
@interface OSCEmoticonPackage ()

@end

@implementation OSCEmoticonPackage

static NSArray *_packageList;

+ (NSArray *)sharePackageList {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _packageList = [OSCEmoticonPackage discriminateEmojiFromEmoticon];
    });
    return _packageList;
}



- (void)appendEmtyEmoticons {
    NSInteger count = self.emoticons.count % emoticonMaxCountPerPage;
    
    for (NSInteger i = count; i < emoticonMaxCountPerPage - 1; i++) {
        self.emoticons = [self.emoticons arrayByAddingObject:[OSCEmoticon emoticonWithIsRemoveButton:NO]];
    }
    self.emoticons = [self.emoticons arrayByAddingObject:[OSCEmoticon emoticonWithIsRemoveButton:YES]];
}

+ (NSString *)pathOfRecent {
    static dispatch_once_t onceToken;
    static NSString *pathOfRecent;
    dispatch_once(&onceToken, ^{
       pathOfRecent = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"recent_emoticons.arch"];
    });
    return pathOfRecent;
}

+ (NSArray *)discriminateEmojiFromEmoticon {
    
    NSDictionary *dict = [OSCEmoticonPackage emojiDict];
    NSArray *allKeys = [dict allKeys];
    NSMutableArray *normalEmoticonsArr = [[NSMutableArray alloc] init];
    NSMutableArray *normalEmojiArr = [[NSMutableArray alloc] init];
    NSMutableArray *emojisArr = [[NSMutableArray alloc] init];
    
    for (NSString *key in allKeys) {
        if ([key hasPrefix:@"["] && [key hasSuffix:@"]"]) {
            [normalEmoticonsArr addObject:@{@"chs" : key,
                                           @"imageName" : dict[key]}];
            
        } else if ([key hasPrefix:@":"] && [key hasSuffix:@":"]){
            [emojisArr addObject:@{@"chs" : key,
                                   @"emojiString" : dict[key]}];
        } else {
            [normalEmojiArr addObject:@{@"chs" : dict[key],
                                            @"imageName" : [dict[key] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]]}];
        }
    }

    
    NSSortDescriptor *chsDesc = [NSSortDescriptor sortDescriptorWithKey:@"chs" ascending:YES];
    [normalEmojiArr sortUsingDescriptors:@[chsDesc]];
    NSSortDescriptor *imageNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"imageName" ascending:YES];
    [normalEmoticonsArr sortUsingDescriptors:@[imageNameDesc]];
    [normalEmoticonsArr addObjectsFromArray:normalEmojiArr];
    OSCEmoticonPackage *normalPackage = [OSCEmoticonPackage new];
    normalPackage.packgeName = @"默认";
    [normalPackage loadEmoticonsWithArray:normalEmoticonsArr];
    [normalPackage appendEmtyEmoticons];
    
    OSCEmoticonPackage *emojiPackage = [OSCEmoticonPackage new];
    emojiPackage.packgeName = @"emoji";
    [emojiPackage loadEmoticonsWithArray:emojisArr];
    
    
    return @[normalPackage,emojiPackage];
}

- (void)loadEmoticonsWithArray:(NSArray *)array {
    NSMutableArray *emoticons = [[NSMutableArray alloc] init];
    NSInteger index = 0;
    for (NSDictionary *dict in array) {
        if (index == emoticonMaxCountPerPage - 1) {
            [emoticons addObject:[OSCEmoticon emoticonWithIsRemoveButton:YES]];
            [emoticons addObject:[[OSCEmoticon alloc] initWithDict:dict]];
            index = 1;
        } else {
            [emoticons addObject:[[OSCEmoticon alloc] initWithDict:dict]];
            index ++;
        }
    }
    self.emoticons = emoticons;
}

+ (NSAttributedString *)emoticonStringFromAttributedString:(NSAttributedString *)attrString {
    
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithAttributedString:attrString];
    NSString *pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]|:[\\+\\-a-zA-Z0-9\\u4e00-\\u9fa5_]+:";
    NSError *error = nil;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray *resultsArray = [re matchesInString:attrString.string options:0 range:NSMakeRange(0, attrString.string.length)];
    
    NSInteger count = resultsArray.count;
    while (count > 0) {
        NSTextCheckingResult *checkingRes = resultsArray[--count];
        
        NSAttributedString *tempAttrString = [attrString attributedSubstringFromRange:checkingRes.range];
        
        OSCEmoticon *emoticon = [OSCEmoticonPackage emoticonFromString:tempAttrString.string];
        if (emoticon) {
            NSAttributedString *attStr = [OSCEmoticonAttachment getEmoticonAttachmentWithEmoticon:emoticon fontSize:15];
            [strM replaceCharactersInRange:checkingRes.range withAttributedString:attStr];
        }
    }
    if (error) {
        return nil;
    }
    return strM;
}

+ (OSCEmoticon *)emoticonFromString:(NSString *)aString {
    OSCEmoticon *emoticon;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"chs == %@",aString];
    for (OSCEmoticonPackage *package in [OSCEmoticonPackage sharePackageList]) {
        emoticon = [package.emoticons filteredArrayUsingPredicate:predicate].lastObject;
        if (emoticon) {
            break;
        }
    }
    return emoticon;
}
+ (NSDictionary *)emojiDict {
    static dispatch_once_t once;
    static NSDictionary *emojiDict;
    
    dispatch_once(&once, ^ {
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"emoji" ofType:@"plist"];
        emojiDict = [[NSDictionary alloc] initWithContentsOfFile:path];
    });
    
    return emojiDict;
}

@end

@interface OSCEmoticon () 

@end

@implementation OSCEmoticon

+ (instancetype)emoticonWithIsRemoveButton:(BOOL)isRemovoButton {
    OSCEmoticon *emoticon = [OSCEmoticon new];
    emoticon.isRemoveButton = isRemovoButton;
    return emoticon;
}

- (instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

@end
